import HandleBtn from '@/components/HandleBar/btn';
import { ModalForm, ProForm, ProFormSelect, ProFormText } from '@/components/Pro';
import { stationControllerList } from '@/services/ess/station';
import {
  versionManageControllerEdit,
  versionManageControllerSave,
  versionManageControllerUpload,
} from '@/services/ess/upgradeVersion';
import { fetchDictInfo } from '@/utils';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Col, InputNumber, message, Row, Select, Space, Upload } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl } from 'umi';

type ModalProps = {
  isEdit: boolean;
  submitSuccess: (data: any) => void;
  formProps?: any;
};
const AddModal: React.FC<ModalProps> = (props) => {
  const { success, error } = message;
  const [repeatedPushTime, setRepeatedPushTime] = useState('');
  const modalFormRef = useRef(null);
  const [timeStamp, setTimeStamp] = useState<string>('minute');
  const { isEdit, submitSuccess, formProps } = props;
  const [packageName, setPackageName] = useState<string>('');
  const [versionFile, setFile] = useState<File>();
  const intl = useIntl();
  const handleGetStationList = async (values) => {
    const params = {
      station: values.keyWords || '',
      current: 1,
      pageSize: 100,
    };
    const res = await stationControllerList(params);
    return res?.data.records.map((item: any) => {
      return {
        label: item.stationName,
        value: item.stationCode,
      };
    });
  };
  useEffect(() => {
    setRepeatedPushTime(formProps?.repeatedPush);
    modalFormRef?.current?.setFieldsValue({ ...formProps });
  }, [formProps]);
  return (
    <>
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        formRef={modalFormRef}
        grid={true}
        initialValues={formProps}
        title={
          isEdit
            ? intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.edit' })
            : intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.addVersion' })
        }
        width="730px"
        colProps={{ md: 24 }}
        trigger={
          isEdit ? (
            <a href={'#'} key="eidt">
              {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.edit' })}
            </a>
          ) : (
            <HandleBtn key="add" handleType="add">
              {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.new' })}
            </HandleBtn>
          )
        }
        onFinish={async (values) => {
          let token = false;
          const params = {
            packageName: packageName,
            repeatedPush: timeStamp === 'minute' ? values.repeatedPush : values.repeatedPush * 60,
            stationRange: values.stationRange,
            deviceType: values.deviceType,
            deviceModel: values.deviceModel,
            version: values.version,
          };
          if (isEdit) {
            const res = await versionManageControllerEdit({
              recordId: formProps.recordId,
              ...params,
            });
            success(res.message);
            token = true;
            submitSuccess(token);
            return token;
          } else {
            const res = await versionManageControllerSave(params);
            if (res.success) {
              const form = new FormData();
              form.append('file', versionFile);
              const verRes = await versionManageControllerUpload(
                {
                  infoId: res?.data?.recordId,
                },
                form,
              );
              if (verRes.success) {
                success(verRes.message);
                token = true;
              }
            }
            submitSuccess(token);
            return token;
          }
        }}
      >
        <ProForm.Group
          title={intl.formatMessage({
            id: 'remoteUpgradeMangment.versionManagement.Basicinformation',
          })}
        >
          <ProFormText
            label={intl.formatMessage({
              id: 'remoteUpgradeMangment.versionManagement.versionNumber',
            })}
            name="version"
            fieldProps={{
              maxLength: 30,
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'remoteUpgradeMangment.requiredFields.versionNumber',
                }),
              },
            ]}
          ></ProFormText>
          <Row>
            <Col span={24}>
              <ProForm.Item
                label={intl.formatMessage({
                  id: 'remoteUpgradeMangment.versionManagement.softwarePackage',
                })}
                name="upgradePackage"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'remoteUpgradeMangment.requiredFields.uploadSoftwarePackage',
                    }),
                  },
                ]}
              >
                <Space>
                  <Upload
                    maxCount={1}
                    accept=".zip, .rar"
                    beforeUpload={(file) => {
                      setPackageName(file.name);
                      setFile(file);
                    }}
                    customRequest={(req) => {
                      const { onSuccess, onError } = req;
                      const { file } = req;
                      if (file.size / 1024 / 1024 > 500) {
                        error(
                          intl.formatMessage({
                            id: 'systemManagement.neddTochange.fileMax500m',
                          }),
                        );
                        onError('文件大小超过500M，请重新上传');
                        return false;
                      } else {
                        onSuccess({ result_status: true });
                      }
                    }}
                  >
                    <Button icon={<UploadOutlined />}>
                      {intl.formatMessage({
                        id: 'remoteUpgradeMangment.versionManagement.clickToUpload',
                      })}
                    </Button>
                  </Upload>
                  <span>{formProps?.packageName}</span>
                </Space>
              </ProForm.Item>
            </Col>

            <Col span={24}>
              <ProForm.Item
                label={intl.formatMessage({
                  id: 'remoteUpgradeMangment.versionManagement.repeatedPush',
                })}
                name="repeatedPush"
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'remoteUpgradeMangment.requiredFields.repeatPushTime',
                    }),
                  },
                ]}
              >
                <Space.Compact>
                  <InputNumber
                    min={'0'}
                    value={repeatedPushTime}
                    onChange={(e) => {
                      setRepeatedPushTime(e);
                    }}
                  ></InputNumber>
                  <Select
                    onChange={(value) => {
                      setTimeStamp(value);
                    }}
                    value={timeStamp}
                    style={{ width: 120 }}
                    defaultValue="minute"
                    options={[
                      {
                        label: intl.formatMessage({
                          id: 'remoteUpgradeMangment.versionManagement.hour',
                        }),
                        value: 'hour',
                      },
                      {
                        label: intl.formatMessage({
                          id: 'remoteUpgradeMangment.versionManagement.minutes',
                        }),
                        value: 'minute',
                      },
                    ]}
                  ></Select>
                </Space.Compact>
              </ProForm.Item>
            </Col>
          </Row>
        </ProForm.Group>
        <ProForm.Group
          title={intl.formatMessage({
            id: 'remoteUpgradeMangment.versionManagement.applicableEquipment',
          })}
        >
          <ProFormSelect
            name="stationRange"
            label={intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.Plantwide' })}
            fieldProps={{
              maxTagCount: 2,
              showSearch: true,
              mode: 'multiple',
            }}
            request={handleGetStationList}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'remoteUpgradeMangment.requiredFields.selectSiteRange',
                }),
              },
            ]}
          ></ProFormSelect>
          <ProFormSelect
            name="deviceType"
            label={intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.deviceType' })}
            request={async () => {
              return await fetchDictInfo(100009);
            }}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'remoteUpgradeMangment.requiredFields.versionNumber',
                }),
              },
            ]}
          ></ProFormSelect>
          <ProFormText
            label={intl.formatMessage({
              id: 'remoteUpgradeMangment.versionManagement.deviceModel',
            })}
            name="deviceModel"
            tooltip={intl.formatMessage({
              id: 'remoteUpgradeMangment.requiredFields.multipleDeviceModels',
            })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'remoteUpgradeMangment.requiredFields.enterDeviceModel',
                }),
              },
            ]}
          ></ProFormText>
        </ProForm.Group>
      </ModalForm>
    </>
  );
};

export default AddModal;
